package jnpf.engine.util;

import cn.hutool.core.collection.CollectionUtil;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.HistoryService;
import org.flowable.engine.ManagementService;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.TaskService;
import org.flowable.engine.history.HistoricActivityInstance;
import org.flowable.engine.impl.persistence.entity.HistoricActivityInstanceEntity;
import org.flowable.task.api.Task;
import org.flowable.task.service.impl.persistence.entity.TaskEntity;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author LoveMyOrange
 * @create 2022-01-12 13:49
 */
@Component
@Slf4j
public class ActivitiNativeTaskQueryUtils {
    @Resource
    private HistoryService historyService;
    @Resource
    private RepositoryService repositoryService;
    @Resource
    private TaskService taskService;
    @Resource
    private ManagementService managementService;
    /**
     * Activiti原生 只能支持一个类型的
     * @return
     */
    public List<HistoricActivityInstance> getSomeTypeActivityInstances(){
        return null;
    }

    /**
     * 判断 发起节点是不是第一次出现
     */
    public Long firstActivityFlag(String firstActivityId,String processInstanceId){
        long count = historyService.createNativeHistoricActivityInstanceQuery()
                .sql("SELECT COUNT(1) FROM " + managementService.getTableName(HistoricActivityInstanceEntity.class) +
                        " WHERE ACT_ID_=#{actId} AND PROC_INST_ID_ =#{processInstanceId}")
                .parameter("actId", firstActivityId)
                .parameter("processInstanceId", processInstanceId)
                .count();
        return count;
    }

    public List<Task> getTasksByProcessInstanceIdAndTaskDefinitionKey(String processInstanceId, List<String> taskDefinitionKeys){
        return taskService.createNativeTaskQuery()
                .sql("SELECT ID_ , NAME_ , ASSIGNEE_ FROM " + managementService.getTableName(TaskEntity.class) +
                        " WHERE PROC_INST_ID_ =#{processInstanceId} AND TASK_DEF_KEY_ IN (#{taskDefinitionKeys})")
                .parameter("processInstanceId", processInstanceId)
                .parameter("taskDefinitionKeys", CollectionUtil.join(taskDefinitionKeys,","))
                .list();
    }



}
